package com.heihei.security.interceptor;

import com.heihei.security.dto.auth.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @author duanhengfei
 * @version 1.0
 * @date 2020/7/4 9:57
 * @since JDK1.8
 */
@Component
public class SimpleAuthentationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在这个方法中，校验用户请求的url是否在用户的权限范围内
        //读取会话信息
        Object userInfoObject = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if(userInfoObject == null) {
            writeContent(response, "请登录");
        }
        UserDto user = (UserDto) userInfoObject;
        //请求的url
        String requestURI = request.getRequestURI();
        if(user.getAuthorities().contains("p1") && requestURI.contains("r1")) {
            return true;
        }
        if(user.getAuthorities().contains("p2") && requestURI.contains("r2")) {
            return true;
        }
        writeContent(response, "权限不足，拒绝访问");
        return false;
    }

    /**
     * 响应输出
     *
     * @author duanhengfei
     * @date 2020年07月04日 10:07:05
     */
    private void writeContent(HttpServletResponse response, String message) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(message);
        writer.close();
        response.resetBuffer();
    }
}